package com.lh.utils;
import com.lh.entity.table.DeadlineNode;
import com.lh.entity.vo.DeathLineNodeDetailVO;
import com.lh.entity.vo.DepartmentSummary;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

public class SmartDepartmentSplitter {

    // 单位清单（按长度降序排序，优先匹配长名称）
    private static final List<String> DEPARTMENTS = RectificationClassifier.DEPARTMENTS;

    /**
     * 基于包含关系的智能拆分（只要包含单位清单中的名称就算匹配）
     * 原理：从左到右扫描，优先匹配最长的有效单位名称，只要包含即视为匹配
     */
    public static List<String> smartSplit(String departmentStr) {
        List<String> result = new ArrayList<>();
        if (departmentStr == null || departmentStr.trim().isEmpty()) {
            return result;
        }

        // 去除字符串中的所有空白字符（处理可能的空格干扰）
        String processed = departmentStr.replaceAll("\\s+", "");
        int start = 0; // 起始索引

        while (start < processed.length()) {
            boolean matched = false;
            // 尝试匹配清单中的单位（已按长度降序，优先长名称）
            for (String dept : DEPARTMENTS) {
                int deptLen = dept.length();
                // 剩余字符串长度不足时跳过
                if (start + deptLen > processed.length()) {
                    continue;
                }
                // 截取子串判断是否包含单位名称（核心修改点）
                String substring = processed.substring(start); // 从当前位置到末尾的子串
                if (substring.contains(dept)) {
                    result.add(dept);
                    // 移动起始索引到匹配的单位名称之后（避免重复匹配）
                    start += substring.indexOf(dept) + deptLen;
                    matched = true;
                    break; // 匹配成功，跳出循环
                }
            }
            // 未匹配到任何单位，移动一个字符继续扫描（避免死循环）
            if (!matched) {
                start++;
            }
        }

        // 去重（避免同一单位被多次匹配）
        return result.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 处理DeadlineNode列表，拆分部门字段（无间隔符场景）
     */
    public static List<DeathLineNodeDetailVO> splitNodes2(List<DeathLineNodeDetailVO> nodes) {
        List<DeathLineNodeDetailVO> result = new ArrayList<>();
        if (nodes == null || nodes.isEmpty()) {
            return result;
        }

        for (DeathLineNodeDetailVO node : nodes) {
            // 尝试从departmentName拆分
            List<String> departments = smartSplit(node.getDepartment());
            // 无匹配单位时保留原始节点
            if (departments.isEmpty()) {
                continue;
            }
            // 为每个匹配到的单位创建新节点
            for (String dept : departments) {
                DeathLineNodeDetailVO newNode = copyNode(node);
                newNode.setDepartment(dept);
                result.add(newNode);
            }
        }

        return result;
    }

    // 复制DeadlineNode对象
    private static DeathLineNodeDetailVO copyNode(DeathLineNodeDetailVO source) {
        DeathLineNodeDetailVO target = new DeathLineNodeDetailVO();
        // 复制所有字段（与之前的copy方法一致）
        target.setWarnLevel(source.getWarnLevel());
        target.setRed(source.getRed());
        target.setWarnLevel(source.getWarnLevel());
        target.setDepartment(source.getDepartment());
        target.setProjectType(source.getProjectType());
        target.setProjectChildType(source.getProjectChildType());
        target.setProjectChildCategoryType(source.getProjectChildCategoryType());
        target.setTotal(source.getTotal());
        return target;
    }



    /**
     * 按部门和项目子分类分组并生成统计结果
     * @param detailList 原始DeathLineNodeDetailVO列表
     * @return 按部门分组的统计结果
     */
    public static List<DepartmentSummary> groupByDepartmentAndProject(List<DeathLineNodeDetailVO> detailList) {
        // 1. 按部门分组（一级分组）
        Map<String, List<DeathLineNodeDetailVO>> departmentGroups = detailList.stream()
                .collect(Collectors.groupingBy(DeathLineNodeDetailVO::getDepartment));

        List<DepartmentSummary> result = new ArrayList<>();

        // 2. 处理每个部门的数据
        for (Map.Entry<String, List<DeathLineNodeDetailVO>> deptEntry : departmentGroups.entrySet()) {
            String department = deptEntry.getKey();
            List<DeathLineNodeDetailVO> deptDetails = deptEntry.getValue();

            // 3. 按项目子分类+项目大类分组（二级分组）
            Map<String, List<DeathLineNodeDetailVO>> projectGroups = deptDetails.stream()
                    // 组合子分类和大类作为分组键（避免同子分类不同大类的混淆）
                    .collect(Collectors.groupingBy(vo ->
                            vo.getProjectChildCategoryType() + "|" + vo.getProjectType()
                    ));

            // 4. 计算部门级总数据
            int totalProjects = deptDetails.size(); // 总项目数
            int totalRed = (int) deptDetails.stream()
                    .filter(vo -> vo.getWarnLevel() != null && vo.getWarnLevel() == 2) // 假设2是红色预警
                    .count();
            int totalGreen = (int) deptDetails.stream()
                    .filter(vo -> vo.getWarnLevel() != null && vo.getWarnLevel() == 0) // 假设0是绿色预警
                    .count();

            // 计算总红色率和总绿色率（保留两位小数）
            String totalRedRate = calculateRate(totalRed, totalProjects);
            String totalGreenRate = calculateRate(totalGreen, totalProjects);

            // 5. 处理项目详情列表
            List<DeathLineNodeDetailVO> projectDetails = new ArrayList<>();
            for (Map.Entry<String, List<DeathLineNodeDetailVO>> projectEntry : projectGroups.entrySet()) {
                List<DeathLineNodeDetailVO> projectVOs = projectEntry.getValue();
                // 解析分组键，获取子分类和大类
                String[] keyParts = projectEntry.getKey().split("\\|");
                String childCategory = keyParts[0];
                String projectType = keyParts.length > 1 ? keyParts[1] : "";

                // 计算该项目分组的统计数据
                int projectTotal = projectVOs.size();
                int projectRed = (int) projectVOs.stream()
                        .filter(vo -> vo.getWarnLevel() != null && vo.getWarnLevel() == 2)
                        .count();
                int projectGreen = (int) projectVOs.stream()
                        .filter(vo -> vo.getWarnLevel() != null && vo.getWarnLevel() == 0)
                        .count();

                // 创建项目详情对象
                DeathLineNodeDetailVO detail = new DeathLineNodeDetailVO();
                detail.setProjectType(projectType);
                detail.setProjectChildCategoryType(childCategory);
                detail.setTotal(projectTotal);
                detail.setRedRate(calculateRate(projectRed, projectTotal));
                detail.setGreenRate(calculateRate(projectGreen, projectTotal));

                projectDetails.add(detail);
            }

            // 6. 创建部门汇总对象
            DepartmentSummary deptSummary = new DepartmentSummary();
            deptSummary.setName(department);
            deptSummary.setTotal(totalProjects);
            deptSummary.setRed(totalRed);
            deptSummary.setTotalRedRate(totalRedRate);
            deptSummary.setTotalGreenRate(totalGreenRate);
            deptSummary.setProjectDetails(projectDetails);

            result.add(deptSummary);
        }

        return result;
    }

    /**
     * 计算比率（分子/分母*100%），保留两位小数
     */
    private static String calculateRate(int numerator, int denominator) {
        if (denominator == 0) {
            return "0.00%";
        }
        BigDecimal rate = new BigDecimal(numerator)
                .divide(new BigDecimal(denominator), 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100))
                .setScale(2, RoundingMode.HALF_UP);
        return rate + "%";
    }



    /**
     * 处理DeadlineNode列表，拆分部门字段（无间隔符场景）
     */
    public static List<DeadlineNode> splitNodes(List<DeadlineNode> nodes) {
        List<DeadlineNode> result = new ArrayList<>();
        if (nodes == null || nodes.isEmpty()) {
            return result;
        }

        for (DeadlineNode node : nodes) {
            // 尝试从departmentName拆分
            List<String> departments = smartSplit(node.getDepartmentName());

            // 如果departmentName无匹配，尝试realDepartment
            if (departments.isEmpty()) {
                departments = smartSplit(node.getRealDepartment());
            }

            // 无匹配单位时保留原始节点
            if (departments.isEmpty()) {
                continue;
            }

            // 为每个匹配到的单位创建新节点
            for (String dept : departments) {
                DeadlineNode newNode = copyNode(node);
                newNode.setDepartmentName(dept);
                newNode.setRealDepartment(dept);
                result.add(newNode);
            }
        }

        return result;
    }

    // 复制DeadlineNode对象
    private static DeadlineNode copyNode(DeadlineNode source) {
        DeadlineNode target = new DeadlineNode();
        // 复制所有字段（与之前的copy方法一致）
        target.setId(source.getId());
        target.setMainId(source.getMainId());
        target.setRectificationId(source.getRectificationId());
        target.setDeadline(source.getDeadline());
        target.setName(source.getName());
        target.setContent(source.getContent());
        target.setDescription(source.getDescription());
        target.setSort(source.getSort());
        target.setState(source.getState());
        target.setTypeName(source.getTypeName());
        target.setCreateTime(source.getCreateTime());
        target.setProgress(source.getProgress());
        target.setRemark(source.getRemark());
        target.setUpdateTime(source.getUpdateTime());
        target.setEndTime(source.getEndTime());
        target.setIsEnd(source.getIsEnd());
        target.setDeadlineType(source.getDeadlineType());
        target.setDuration(source.getDuration());
        target.setWarnLevel(source.getWarnLevel());
        target.setRed(source.getRed());
        target.setYellow(source.getYellow());
        target.setGreen(source.getGreen());
        target.setTotal(source.getTotal());
        target.setRate(source.getRate());
        target.setRateSort(source.getRateSort());
        target.setStreet(source.getStreet());
        return target;
    }


}